<?php namespace App\Http\Controllers;

use App\Models\Goods as MGoods;
use App\Models\ShopCar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Goods extends Controller
{
    public function index(Request $request)
    {
//        $page = $request->input('page');
        $query = DB::table('goods')->select('*');
        if ($filterText = $request->input('filter.text')) {
            $query->where('goods.type_id', $filterText);
        }
        return $query->get();
    }

    //获取商品对象
    public function show($id)
    {
        $goods = MGoods::find($id);
        return response()->json($goods);
    }

    //添加商品
    public function store(Request $request)
    {
        // 表单验证，配合前台验证
        $this->validate($request, [
            'image' => 'required',
            'money' => 'required',
            'type_id' => 'required',
        ]);
        $goods = new MGoods;
        $goods->image = $request->input('image');
        $goods->money = $request->input('money');
        $goods->type_id = $request->input('type_id');
        $goods->title = $request->input('title');
        $goods->number = $request->input('number');
        $goods->save();
        return response()->json($goods->id);
    }

    //修改商品
    public function update(Request $request, $id)
    {
        // 表单验证，配合前台验证
        $this->validate($request, [
            'money' => 'required',
            'type_id' => 'required',
        ]);
        $goods = MGoods::find($id);
        $goods->image = $request->input('image');
        $goods->money = $request->input('money');
        $goods->type_id = $request->input('type_id');
        $goods->title = $request->input('title');
        $goods->number = $request->input('number');
        $goods->save();
        return response()->json($goods->id);
    }

    //删除商品
    public function destroy($id)
    {
        $goods = MGoods::find($id);
        if (!$goods) {
            return response('传参错误，未找到对象！', 500);
        }
        $goods->delete();
        return response('', 200);
    }

    // 加入购物车
    public function shopCar(Request $request, $id)
    {
        // 表单验证，配合前台验证
        $this->validate($request, [
            'money' => 'required',
            'number' => 'required',
        ]);
        $shop_car = ShopCar::where('goods_id', $id)->first();
        if ($shop_car) {
            $shop_car->number += $request->input('number');
            $shop_car->money += $request->input('money');
        } else {
            $shop_car = new ShopCar;
            $shop_car->user_id = 2;
            $shop_car->goods_id = $id;
            $shop_car->number = $request->input('number');
            $shop_car->money = $request->input('money');
        }
        $shop_car->save();
        return response()->json($shop_car->id);
    }
}
